const bd = require('../bd/index')
var COS = require('cos-nodejs-sdk-v5');
const { appendFile } = require('fs');
const { send } = require('process');
const { log } = require('console');
// var fs = require("../public../../public/image");//直接引入文件系统模块

var cos = new COS({
    SecretId: 'AKIDOaWBZhY8RVHm0zh8IBn8CzVkhNnvmMfh', // 身份识别 ID
    SecretKey: 'yf5F8k48vQebIhpgHbeQwB8oDMEp8BwQ', // 身份密钥
});
// 方法数据
const dataFn=(re)=>{
    let obj={}
    let data=[]
        let ind = 0
        let inds = 0
    re.forEach((item,inde) =>{
        ind = 0
        data.forEach(itemx=>{
            if(obj.name === itemx.name) {
                inds =0
                obj={}
            }
        })
        if(inds ===1) data.push(obj)
        inds =0
        obj={}
        //  const index = item.img_name.lastIndexOf('-')
        //  const lastindex =item.img_name.lastIndexOf('/')
         const cen =item.img_s
         re.forEach(itemy =>{
            // const indexy = itemy.img_s.lastIndexOf('-')
            // const lastindexy =itemy.img_name.lastIndexOf('/')
            // const ceny =itemy.img_name.slice(indexy +4,lastindexy)
         const ceny =itemy.img_s
        if(cen === ceny){
            ind++
            if(ind ===1) {
                inds =  1
                obj.name =itemy.img_s
                obj.mark =itemy.img_remark
                obj.Logo = itemy.img_s
                obj.id = itemy.img_id
                obj.children  =[]
               
            }

            obj.children.push( itemy.img_url )
        }
        data.forEach(itemx=>{
            if(obj.name === itemx.name) {
                inds =0
            }
        })
        if(inds ===1) data.push(obj)

         })
    })
    return data
}
// 查询 方法
const ListFn=(req,res,sql)=>{
    var query = req.query 
    var num =query.currentPage 
    var total =null
    if(num>1) {
        num =(num-1)*query.size
    }else{
        num =`0`
    }
    bd.query(`SELECT * FROM ${sql}`,(err,re)=>{
        total= re.length

    })
    bd.query(`SELECT * FROM ${sql} LIMIT ${num},${query.size}`, (err, re) => {
        if (err) {
            res.send({
                code: 440,
                msg: err.sqlMessage
            })
        } else {
            const data = re.map(item => ({
                name: item.user_name,
                age: item.age,
                id: item.user_id,
                careId: item.care_id,
                iphone: item.iphone,
                date: item.date,
                wages_random:item.wages_random,
                working_random:item.working_random
            }))
            res.send({
                code: 200,
                total,
                data: data,
                msg: '查询成功'
            })
        }
    })
}
// 查询 指弹/弹唱/分页方法
const GuitarFn=(req,res,sql)=>{
    var query = req.query|| req.param || req.body
    var num =query.currentPage 
   
    if(num>1) {
        num =(num-1)*query.size
    }else{
        num =`0`
    }
    bd.query(`SELECT * FROM ${sql}`,(err,re)=>{
      const data =  dataFn(re).slice(num,query.size*query.currentPage)
      if(err){
res.send({
    code:500,
    msg:err.sqlMessage
})
      }else{
        res.send({
            code:200,
            data:data,
            msg:'获取成功',
            total: dataFn(re).length
        })
      }
       
    
    })

}
 // 查询 弹唱条件 方法
 const SearchFn =(req,res,sql)=>{
     let data=[]
    bd.query(`SELECT * FROM ${sql}`,(err,re)=>{
      dataFn(re).map(item => {
        if(item.name.includes(req.query.name)){
            data.push (item)
        }
      })
      sendFn(res,err,'查询成功','服务器错误',data,data.length)
    })
   
 }
 const sendFn=(res,err,msg,errMsg,re,total)=>{
    if(err){
        res.send({
            code:500,
            msg:errMsg||err.sqlMessage
        })

    }else{
       res.send({
        total,
           code:200,
           data:re,
           msg:msg||'操作成功'
       })
    }
 }
// 删除 指弹/弹唱 数据
let list =[]

    let id =[]
const delguitarFn = async(req,res,sql)=>{
    id =[]
    bd.query(`SELECT * FROM ${sql}`,(err,re)=>{
             list =req.body
            //  const lists = list.map(item=>  ({Key:`${item}/`}))
            //  console.log(lists);
            //  deltxy(lists)
            list.forEach(item =>{
           re.forEach(itemy => {
               if( itemy.img_s === item){
                if(id.indexOf(itemy.img_id) == -1)  id.push(itemy.img_id)
               }
              })
             })
    })
setTimeout(()=>{
    if(id.length ==0||id==null) return res.send({code:501,msg:'服务器错误'})
    bd.query(`delete from ${sql} where img_id in (${id})`,(err,re)=>{
        sendFn(res,err,'删除成功','服务器错误',)
        if(!err){
            // const lists = list.map(item=>  ({Key:`${item}`}))
            // console.log(lists);
            // deltxy(lists)
        }
    })
},500)
}
// 推荐吉他谱 方法
const Recommend=(req,res,sql)=>{
bd.query('')

}
//  评论
// const FeedbackReviewsFn=(req,res,sql)=>{
//     let {founder_id,founder,founder_comment,date} = req.body
//     bd.query(`insert into ${sql} (founder_id,founder,founder_comment,date), values(?,?,?,?)`,[founder_id,founder,founder_comment,date],(err,re)=>{
       
//         sendFn(res,err,'发布成功','服务器错误',re,re.length)
//     })
// }

const TreeData = (data, name,id) =>{
    const arr = []
    let obj={}
    data.forEach(item => {
      if (item.id === id && item.founder == name) {
        // obj.founder=item.founder
        // obj.id=item.id
        // obj.founder_id=item.founder_id
        // obj.comment= item.comment
        // obj.children=[]
        const children = TreeData(data, item.founder,item.founder_id)
        if (children.length) {
          itme.children = children
        }
        obj.children.push(itme)
      }
    })
    return arr.push(obj)
  }
  // 查询 反馈
  const FeedbackReviewsFn =(req,res)=>{
  let obj ={}
let ind =0
let arr =[]
let app=0
    bd.query(`SELECT * FROM comment`,(err,re)=>{
      
        re.forEach((item,index) =>{
            app=0
            ind =0
            obj ={}
            re.forEach(itemy =>{
                if(item.id === itemy.founder_id && item.founder == itemy.chuangjian){
                  
                    ind ++
                   if(ind==1){
                    obj.founder=item.founder
                    obj.id=item.id
                    obj.founder_id=item.founder_id
                    obj.comment= item.comment
                    obj.children=[]
                  
                   }
                   obj.children.push({
                   id:itemy.id,
                    reply_id:itemy.reply_id,
                    reply_comment:itemy.reply_comment,
                    reply:itemy.founder,
                    chuangjian:itemy.chuangjian
                   } )
                   const arrt=[]
                   obj.children.forEach(itemx =>{
                    re.forEach(itemp =>{
                        if(itemx.id === itemp.founder_id && itemp.founder == itemx.chuangjian){
                           
                            arrt.push(itemp)
                            obj.children.push({
                                children:arrt
                            })
                           
                        }
                    })
                  
                })
                }else{
                    if(item.comment==null)  app =1
                    obj.founder=item.founder
                    obj.id=item.id
                    obj.founder_id=item.founder_id
                    obj.comment= item.comment
                   
                }
              
            })
          
            if( app ===0)arr.push(obj)
        })
        sendFn(res,err,'添加成功','服务器错误',arr)
    })
  }
  // 添加反馈
  const addFeedbackReviewsFn =(req,res)=>{
      console.log('add');
      let {founder_id,founder,founder_comment} = req.body
    bd.query(`insert into comment (founder_id,founder,comment) values(?,?,?)`,[founder_id,founder,founder_comment],(err,re)=>{
        sendFn(res,err,'发表成功',)
    })
  }
   // 回复 反馈
   const ReplyFeedbackReviewsFn =(req,res)=>{
    let {founder,reply_id,reply,reply_comment,date,id} = req.body
  bd.query(`insert into comment (chuangjian,founder,founder_id,reply_id,reply_comment) values(?,?,?,?,?)`,[founder,reply,id,reply_id,reply_comment],(err,re)=>{
      sendFn(res,err,'回复成功',)

  })
}
    // 删除反馈
    const delFeedbackReviewsFn =(req,res)=>{
        let {id} = req.query
      bd.query(`delete from comment where id in (${id})`,(err,re)=>{
          sendFn(res,err,'删除成功',)
      })
    }
// 查询评论
const InquiryCommentFn=(req,res,sql)=>{
    bd.query(`SELECT * FROM ${sql} WHERE feedback_id = ${req.query.id}`,(err,re)=>{

       console.log( TreeData(re,req.query.id));



 
       
        if(err){
            res.send({
                code:500,
                msg:err.sqlMessage
            })
    
        }else{
           res.send({
          
               code:200,
               data: [ 
                {
                    feedback_id:162,
                    founder_id:3,
                    founder:'张三',
                    founder_comment:'这是什么玩意',
                children:[  
                 {
                    reply_id:2,
                    reply:'李四',
                    reply_comment:'你会不会说话啊',
                  children:[{
                    founder_id:3,
                    founder:'王五',
                    founder_comment:'这是什么玩意啊'
                        },{
                            founder_id:3,
                            founder:'双面柜',
                            founder_comment:'这是什么玩意啊'
                                },
                    ]
                        },
                        {
                            reply_id:2,
                            reply:'小王',
                            reply_comment:'你会不会说话啊',
                          children:[{
                            founder_id:3,
                            founder:'大王',
                            founder_comment:'这是什么玩意啊',
                            children:[{
                                reply_id:2,
                                reply:'李四',
                                reply_comment:'你会不会说话啊',
                            }]
                                }]
                                }
                ]
                
             },

             {
                feedback_id:163,
                founder_id:3,
                founder:'王五',
                founder_comment:'有人在吵架',
            children:[  
             {
                reply_id:2,
                reply:'赵六',
                reply_comment:'......',
              children:[]
                    }
            ]
            
            },



             {
                feedback_id:163,
                founder_id:3,
                founder:'王五',
                founder_comment:'有人在吵架',
            children:[  
             {
                reply_id:2,
                reply:'赵六',
                reply_comment:'......',
              children:[]
                    }
            ]
            
            }
            ],
               msg:'操作成功'
           })
        }

        // sendFn(res,err,'发布成功','服务器错误',re,re.length)
    })
}
// 添加
const addFn=(req,res)=>{
    var param = req.body || req.params;
    bd.query("insert into workerinfo ( user_name, age, care_id,iphone) values(?,?,?,?)", [param.name, param.age, param.careId,param.iphone], (err, re) => {
        sendFn(res,err,'添加成功',)
    })
}
// 查询随机数
const randomList=(req,res)=>{
bd.query('SELECT * FROM randoms',(err,re)=>{
    sendFn(res,err,'查询成功','服务器错误',re[0])
})
}
// 随机数添加
const addrandomFn=(req,res)=>{
    var param = req.body || req.params;
   
    bd.query(`update randoms set wagesMax = ${param.wagesMax},wagesMin = ${param.wagesMin},workingMax = ${param.workingMax},workingMin = ${param.workingMin} where id = 0 `, 
   (err, re) => {
        if (err) {
            console.log(err.sqlMessage);
           res.send({code:500,msg:err.sqlMessage})
        } else {
            res.send({
                code: 200,
                msg: '添加成功',
               
            })
        }
    })
}

// 修改
const Edilt = (req,res) =>{
    var param = req.body || req.params || req.query
   

    bd.query(`update workerinfo set user_name = '${param.name}',age=${param.age} ,care_id=${param.careId}  where user_id= ${param.id}`,(err,re)=>{
    if (err) {
       res.send({code:500,msg:'服务器错误'})
    } else {
        res.send({
            code: 200,
            msg: '修改成功'
        })
    }
})
}
// 删除数据
const delFn=(req,res)=>{
    let arrs =[]
    req.body.forEach(item =>{
        arrs.push(item.id)
    })
  
    bd.query(`delete from workerinfo where user_id in (${[...arrs]})`,(err,re)=>{
        if (err) {
            res.send({code:500,msg:'服务器错误'})
         } else {
             res.send({
                 code: 200,
                 msg: '删除成功'
             })
            }
    })
}

let arr =[]
let opt =0
let time =0
// 删除 txy 
const deltxy =(nameList)=>{
    console.log(nameList);
    cos.deleteMultipleObject({
        Bucket: 'guitar-img-1307419551', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Objects: nameList
    }, function(err, data) {
        console.log(err || data);
    });
}
// 上传txy
const uptxy=(filePath,name,obj)=>{
arr =[]
opt =0
time++
    filePath.forEach((item,index) =>{
        arr.push( {
                Bucket: 'guitar-img-1307419551', /* 填入您自己的存储桶，必须字段 */
                Region: 'ap-nanjing',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
                Key: `${obj.name}-${time}/${obj.name}-${index+1}`,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
                FilePath: item,
                onTaskReady: function(taskId) {
                  /* taskId可通过队列操作来取消上传cos.cancelTask(taskId)、停止上传cos.pauseTask(taskId)、重新开始上传cos.restartTask(taskId) */
                }
            })
        if(obj.type == '0'){
            console.log(`${name}-${index+1}`);
            bd.query("insert into guitarset( img_name,img_remark,img_url,img_s) values(?,?,?,?)",[obj.name,obj.mark,`https://guitar-img-1307419551.cos.ap-nanjing.myqcloud.com/${obj.name}-${time}/${obj.name}-${index+1}`,`${obj.name}-${time}`],(err,re)=>{
            })
        }else{
            console.log(`${name}-${index+1}`);
            bd.query("insert into burgeeset( img_name,img_remark,img_url,img_s) values(?,?,?,?)",[obj.name,obj.mark,`https://guitar-img-1307419551.cos.ap-nanjing.myqcloud.com/${obj.name}-${time}/${obj.name}-${index+1}`,`${obj.name}-${time}`],(err,re)=>{
            })
        }
    })
  
    cos.uploadFiles({
        files: arr,
        SliceSize: 1024 * 1024 * 20,    /* 设置大于10MB采用分块上传 */
        onProgress: function (info) {
            var percent = parseInt(info.percent * 10000) / 100;
            var speed = parseInt(info.speed / 1024 / 1024 * 100) / 100;
            console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
        },
        onFileFinish: function (err, data, options) {
            console.log(options.Key + '上传' + (err ? '失败' : '完成'));
        },
    }, function (err, data) {
        console.log(err || data);
        
    });


}
module.exports = {
    ReplyFeedbackReviewsFn,
    delFeedbackReviewsFn,
    addFeedbackReviewsFn,
    FeedbackReviewsFn,
    InquiryCommentFn,
    uptxy,
    deltxy,
    delguitarFn,
    SearchFn,
    GuitarFn,
    delFn,
    ListFn,
    addFn,
    Edilt,
    addrandomFn,
    randomList}
